package com.woniu.crowd.service.comsumer;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.crowd.infra.config.AlipayConfig;
import com.woniu.crowd.infra.model.CrowdOrder;
import com.woniu.crowd.service.CrowdOrderService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
@RocketMQMessageListener(topic = "LXLG-find-crowd-pay", consumerGroup = "LXLG-find-crowd-pay")
public class CrowdOrderFindPayConsumer implements RocketMQListener<String> {
    @Resource
    private CrowdOrderService crowdOrderService;

    private ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public void onMessage(String message) {
        System.out.println("支付回查");
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //请求接口
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + message + "\"," + "\"trade_no\":\"" + "" + "\"}");
        //转换格式
        String result = "";
        try {
            result = alipayClient.execute(alipayRequest).getBody();
            Map<String, Map<String, String>> maps = objectMapper.readValue(result, Map.class);
            Map<String, String> date = maps.get("alipay_trade_query_response");
            String state = date.get("trade_status");
            String orderNum = date.get("out_trade_no");
            if (state != null && state.equals("TRADE_SUCCESS")) {
                System.out.println("查询到订单支付成功");
                System.out.println("查看支付逻辑是否处理");
                CrowdOrder crowdOrder = crowdOrderService.getOne(new QueryWrapper<CrowdOrder>().eq("crowd_order_num", orderNum));
                if (crowdOrder.getCrowdOrderState().equals("CREATE")) {
                    System.out.println("执行支付以后得到逻辑");
                    crowdOrderService.setPayOk(message);
                } else {
                    System.out.println("不处理");
                }
            }


        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
